package interceptor;

import com.edu.HandlerDefinition;
import util.HandlerInvoke;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

public class InterceptorChain {

    //private Stack<Interceptor> interceptors = new Stack<>();

    private List<Interceptor> interceptors = new ArrayList<>();

    private HandlerDefinition definition;

    private Iterator<Interceptor> iterator;

    /*public Stack<Interceptor> getInterceptors(){
        return interceptors;
    }*/
    public void getIterator(){
        this.iterator = interceptors.iterator();
    }

    public void add(Interceptor interceptor){
        interceptors.add(interceptor);
    }

    public HandlerDefinition getDefinition() {
        return definition;
    }

    public void setDefinition(HandlerDefinition definition) {
        this.definition = definition;
    }

    public Object handle(){
        Object result = null;
        try {
            /*Stack<Interceptor> interceptors = this.getInterceptors();
            if (interceptors.isEmpty() == false && result == null) {
                Interceptor pop = interceptors.pop();
                result = pop.intercept(this);
            } else {
                HandlerInvoke handlerInvoke = new HandlerInvoke();
                result = handlerInvoke.invokeBB(this.getDefinition());
                System.out.println("handle");
            }*/
            if (iterator.hasNext()){
                result = iterator.next().intercept(this);

            }else {
                HandlerInvoke handlerInvoke = new HandlerInvoke();
                result = handlerInvoke.invokeBB(this.getDefinition());
                System.out.println("handle");
            }
        }catch (Exception e){
            System.out.println("执行invokeBB发生的异常");
        }
        return result;
    }
}
